import { existsSync, mkdirSync } from 'fs';
import path from 'path';

function curring(fn) {
  // 存储每次调用的时候传入的变量
  const inner = (args: any[] = []) => {
    // 存储每次调用时传入的参数
    return args.length >= fn.length
      ? fn(...args)
      : (...userArgs) => inner([...args, ...userArgs]); // 递归返回函数
  };
  return inner();
}
// 我们的柯里化登场： 让函数变得更具体一些，反柯里化： 让函数范围变的更大一些
function isType(typing: string, val) {
  return Object.prototype.toString.call(val) == `[object ${typing}]`;
}

interface IType {
  isString?: any;
  isNumber?: any;
  isBoolean?: any;
  isNull?: any;
  isUndefined?: any;
  isArray?: any;
  isObject?: any;
  [key: string]: any;
}

export const checkType: IType = {};
['String', 'Number', 'Boolean', 'Null', 'Undefined', 'Array', 'Object'].forEach(
  (type) => {
    checkType['is' + type] = curring(isType)(type);
  },
);

/**
 * @param data 数据源
 * @param id字段 默认 'id'
 * @param parent_id 父节点字段 默认 'parent_id'
 * @param children 孩子节点字段 默认 'children'
 * @param rootId 根Id 默认 0
 * @return {{obj, list: Array}}
 */

export function handleTree(
  data,
  id = 'id',
  parent_id = 'parent_id',
  children = 'children',
  rootId = 0,
) {
  const obj = {};
  data.forEach((item) => {
    item[children] = [];
    obj[item[id]] = item;
  });
  const tree = [];
  data.forEach((list) => {
    if (list[parent_id] !== rootId) {
      obj[list[parent_id]][children].push(list);
    } else {
      tree.push(list);
    }
  });
  return {
    tree,
    obj,
  };
}

// 递归创建目录 同步方法
export function mkdirsSync(dirname) {
  if (existsSync(dirname)) {
    return true;
  }
  if (mkdirsSync(path.dirname(dirname))) {
    mkdirSync(dirname);
    return true;
  }
}
